<template>
    <div id="add-edit-RiskZoning">
        <el-dialog
            :title="titleCon"
            v-model="isUseDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="60%" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="140px" :rules="rules">
                <el-row>
                    <el-divider content-position="left">分区信息</el-divider>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="分区名称" prop="v_Name">
                            <el-input v-model="ruleForm.v_Name" placeholder="请输入分区名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="风险分区类型" prop="v_Type">
                            <el-select 
                                filterable
                                class="m-2" 
                                placeholder="请选择风险分区类型" 
                                v-model="ruleForm.v_Type" 
                                @change="typeChange"
                            >
                                <el-option
                                    v-for="item in typeOption"
                                    :key="item.id"
                                    :label="item.value"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="所属位置空间">
                            <el-cascader
                                v-model="ruleForm.l_SpatialLocationId"
                                :options="locationOption" 
                                :props="locationProps"
                                @change="locationChange"
                                filterable
                                clearable 
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="危险源等级">
                            <el-select 
                                filterable
                                class="m-2" 
                                placeholder="请选择危险源等级" 
                                v-model="ruleForm.n_DangerSourceLevel" 
                                @change="levelChange"
                            >
                                <el-option
                                    v-for="item in levelOption"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="主管部门" prop="l_ResponsibleDepId">
                            <el-cascader 
                                v-model="ruleForm.l_ResponsibleDepId"
                                :options="orgOption" 
                                :props="orgProps" 
                                @change="orgChange"
                                filterable
                                clearable 
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="负责人" prop="v_ResponsibleMan">
                            <el-select 
                                filterable
                                class="m-2" 
                                placeholder="请选择负责人" 
                                v-model="ruleForm.v_ResponsibleMan" 
                            >
                                <el-option
                                    v-for="item in responsibleOption"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.name"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="风险分析对象编码">
                            <el-input v-model="ruleForm.v_RISK_OBJECT_CODE" placeholder="请输入风险分析对象编码" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="是否重大危险源">
                            <el-switch
                                v-model="ruleForm.isGreateDangerSource"
                                active-color="#07AAF9"
                                inactive-color="#FF5F33"
                                inline-prompt
                                active-text="是"
                                inactive-text="否"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
                
                <el-divider content-position="left">报警类型</el-divider>
                <div style="display: flex;align-items: center;">
                    <el-form-item label="闯入" label-width="80px" style="margin-bottom: 0px;">
                        <el-switch
                            v-model="ruleForm.isAlarmIntrude"
                            active-color="#07AAF9"
                            inactive-color="#FF5F33"
                            inline-prompt
                            active-text="是"
                            inactive-text="否"
                        />
                    </el-form-item>

                    <el-form-item label="超员" label-width="80px" style="margin-bottom: 0px;">
                        <el-switch
                            v-model="ruleForm.isAlarmOverman"
                            active-color="#07AAF9"
                            inactive-color="#FF5F33"
                            inline-prompt
                            active-text="是"
                            inactive-text="否"
                        />
                    </el-form-item>

                    <el-form-item label="串岗" label-width="80px" style="margin-bottom: 0px;">
                        <el-switch
                            v-model="ruleForm.isAlarmSerialPosts"
                            active-color="#07AAF9"
                            inactive-color="#FF5F33"
                            inline-prompt
                            active-text="是"
                            inactive-text="否"
                        />
                    </el-form-item>

                    <el-form-item label="静止" label-width="80px" style="margin-bottom: 0px;">
                        <el-switch
                            v-model="ruleForm.isAlarmStill"
                            active-color="#07AAF9"
                            inactive-color="#FF5F33"
                            inline-prompt
                            active-text="是"
                            inactive-text="否"
                        />
                    </el-form-item>
                </div>
            </el-form>
            <template #footer>
                <el-button @click="cancelUseClick">取 消</el-button>
                <el-button type="primary" :disabled="repeatDis" :loading="repeatDis" @click="submitForm(ruleFormRef)">提 交</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , computed , toRef , toRefs , toRaw , onMounted , watch } from 'vue'
import { FormInstance, FormRules, ElButton, ElCol, ElDatePicker, ElDialog, ElForm, ElFormItem, ElInput, ElOption, ElRow, ElSelect } from 'element-plus'
import { sysOrgTree, sysEmpSelector } from '/@/api/centerControl/pubilc';
import { 
    sysDictDataList , 
    SMSDCRiskPartitionAdd , 
    SMSDCRiskPartitionUpdate,
    LocationTree,
 } from '/@/api/centerControl/sms';
import axios from 'axios';

/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    id?: Number,
    v_Name: String, // 分区名称
    v_Type: String, // 风险分区类型
    l_SpatialLocationId: any, // 所属空间位置ID传给后端接口
    l_ResponsibleDepId: any, // 责任部门ID传给后端接口
    v_ResponsibleMan: String, // 责任人
    isAlarmIntrude: Boolean, // 报警类型-闯入
    isAlarmOverman: Boolean, // 报警类型-超员
    isAlarmSerialPosts: Boolean, // 报警类型-串岗
    isAlarmStill: Boolean, // 报警类型-静止
    isGreateDangerSource: Boolean, // 是否重大危险源
    n_DangerSourceLevel: Number, // 危险源等级
    v_RISK_OBJECT_CODE: String, // 风险分析对象编码
}
export default defineComponent( {
    name: 'add-edit-RiskZoning',
    components: {},
    props: {
        isUseDialog:{
            type: Boolean,
            default: false,
        },
        repairInfo: {
            type: String,
            default: ''
        }
    },
    setup(props,ctx){
        const titleCon = ref();
        const ruleFormRef = ref();
        const modeOption = ref();
        const typeOption = ref();
        const orgOption = ref();
        const locationOption = ref();
        const responsibleOption = ref();

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })

        /*** 危险源等级改变事件 */
        const levelChange = (val: any) => {
            state.ruleForm.n_DangerSourceLevel = val;            
        }

        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            // 分区名称
            v_Name: [
				{ required: true, message: '请输入分区名称', trigger: 'blur' },
			],
            // 风险分区类型
            v_Type: [
				{ required: true, message: '请选择风险分区类型', trigger: 'change' },
			],
            // 责任部门
            l_ResponsibleDepId: [
				{ required: true, message: '请选择责任部门', trigger: 'change' },
			],
            // 责任人
            v_ResponsibleMan: [
				{ required: true, message: '请输入责任人', trigger: 'change' },
			],
            // 所属区域
            l_SpatialLocationId: [
                { required: true, message: '请选择所属区域', trigger: 'change' },
            ],
        })

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            ctx.emit('cancelUseClick')
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            ctx.emit('cancelUseClick')
        }

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!formEl) return
            formEl.validate( async (valid) => { 
                if(valid){
                    let param = toRaw(state.ruleForm);
                    console.log(param,'param')
                    state.repeatDis = true;
                    try{
                        let res:any;
                        if(props.repairInfo === ''){
                            res = await SMSDCRiskPartitionAdd(param);
                        }else{
                            res = await SMSDCRiskPartitionUpdate(param);
                        }
                        if(res.success){
                            state.repeatDis = false;
                            ctx.emit('updateData');
                            ctx.emit('controlUseClick');
                        }else{
                            state.repeatDis = false;
                            ctx.emit('controlUseClick');
                        }
                    }catch(error){ state.repeatDis = false; }
                }else{
                    console.log('error submit!')
					return false
                }
            })
        }

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
        }

        /*** getTree 获取组织架构树 */
        const getTree = async() => {
            let param = {}
            let res: any = await sysOrgTree(param);
            if(res.success) orgOption.value = res.data;

            let ras: any = await sysEmpSelector({});
            responsibleOption.value = ras.data;
        }

        /*** getDictFun 获取课程类型字典值 */
        const getDictFun = async() => {
            let param: any = {};
            param.TypeCode = 'PartitionType';
            let res: any = await sysDictDataList(param);
            if(res.success) typeOption.value = res.data;

            let params: any = {};
            params.N_Id = 0;
            params.N_GroupId = 0;
            params.N_HeadId = 0;
            let ras: any = await LocationTree(params);
            if(ras.success) locationOption.value = ras.data;
        }

        /*** orgChange 选择部门改变事件 */
        const orgChange = (val: any) => {
            if(val){
                let len = val.length;
                state.ruleForm.l_ResponsibleDepId = val[len - 1];
            }
        }

        /*** 所属区域改变事件 */
        const locationChange = (val: any) => {
            if(val){
                let len = val.length;
                state.ruleForm.l_SpatialLocationId = val[len - 1];
            }
        }

        /*** typeChange 演练类型选择事件 */
        const typeChange = () => {};

        /*** modeChange 演练方式选择事件 */
        const modeChange = () => {};

        /*** 监听isUseDialog的变化 */
        watch(() => props.isUseDialog,(newVal) => {
            if(newVal){
                // 状态数据重置
                state.repeatDis = false;
                getTree();
                getDictFun();
                if(props.repairInfo !== ''){
                    titleCon.value = '编辑'
                    let getData = JSON.parse(props.repairInfo);
                    console.log(getData,'getData')
                    state.ruleForm = getData;
                }else{
                    titleCon.value = '新增';
                    state.ruleForm = {
                        v_Name: '', // 分区名称
                        v_Type: '', // 风险分区类型
                        l_SpatialLocationId: '', // 所属空间位置
                        l_ResponsibleDepId: '', // 责任部门
                        v_ResponsibleMan: '', // 责任人
                        isAlarmIntrude: true, // 报警类型-闯入
                        isAlarmOverman: true, // 报警类型-超员
                        isAlarmSerialPosts: true, // 报警类型-串岗
                        isAlarmStill: true, // 报警类型-静止
                        isGreateDangerSource: false, // 是否重大危险源
                        n_DangerSourceLevel: 1, // 危险源等级
                        v_RISK_OBJECT_CODE: '', // 风险分析对象编码
                    }
                }
            }
        })

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        })

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            titleCon,
            ...toRefs(state),
            isUseDialog,
            rules,
            modeOption,
            modeChange,
            typeOption,
            typeChange,
            orgProps: { checkStrictly: true , label: 'title', value: 'id', children: 'children' },
            orgOption,
            orgChange,
            levelOption: [
                {label: '一级', value: 1},
                {label: '二级', value: 2},
                {label: '三级', value: 3},
                {label: '四级', value: 4},
                {label: '非重大危险源', value: 9}
            ],
            levelChange,
            locationOption,
            locationProps: { checkStrictly: true , label: 'v_FullName', value: 'n_Id', children: 'children' },
            locationChange,
            responsibleOption,
        }
    },
} )
</script>
<style scoped lang="scss">
:deep(.el-cascader){
    width: 100%;
}
:deep(.el-select){
    width: 100%!important;
}
:deep(.el-input){
    width: 100%;
}
</style>